<?php

/**
	Bandit Liked Module

	The contents of this file are subject to the terms of the GNU General
	Public License Version 2.0. You may not use this file except in
	compliance with the license. Any of the license terms and conditions
	can be waived if you get permission from the copyright holder.

	Copyright (c) 2011 Bandit Media
	Jermaine Marée

		@package BanditLiked
		@version 1.4.0
**/

//! Bandit Liked
class BanditLiked extends FeatherBase {

	/**
		Initialize module
			@public
	**/
	static function init() {
		// Add AJAX actions
		add_action('wp_ajax_bandit_liked_ajax',__CLASS__.'::update_liked_count');
		add_action('wp_ajax_nopriv_bandit_liked_ajax',__CLASS__.'::update_liked_count');
	}

	/**
		Update liked count
			@public
	**/
	static function update_liked_count() {
		// get post ID
		$id = $_POST['id'];
		$metakey='_bandit_liked';
		// get liked count
		$count=get_post_meta($id,$metakey,TRUE);
		// check for count
		if(!$count)
			$count=0;
		// increase by 1
		$count++;
		if(isset($_COOKIE['_bandit_liked'])) {
			$cookie=base64_decode($_COOKIE['_bandit_liked']);
			$liked=explode('|',$cookie);
			if(!in_array($id,$liked)) {
				$status=update_post_meta($id,$metakey,$count);
				$cookie=$cookie.'|'.$id;
			} else {
				$status=FALSE;
			}
		} else {
			// update liked count
			$status=update_post_meta($id,$metakey,$count);
			$cookie=$id;
		}
		if($status) {
			setcookie('_bandit_liked',base64_encode($cookie),time()+3600*24*365,'/');
		}
		// generate the response
		$response = json_encode(
			array(
				'success' => $status,
				'postID' => $id,
				'count' => $count
			)
		);
		// JSON header
		header('Content-type: application/json');
		echo $response;
		die();
	}

}